package com.psct;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.security.MessageDigest;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.util.Log;

import com.psct.imageCache.ImageCache;
import com.psct.imageCache.ImageCacheManager;
import com.psct.web.HttpUtil;

public class PSCTUtil {

	/**
	 * MD5
	 * 
	 * @param s
	 * @return
	 */
	public final static String MD5(String s) {
		try {
			byte[] btInput = s.getBytes();
			MessageDigest mdInst = MessageDigest.getInstance("MD5");
			mdInst.update(btInput);
			byte[] md = mdInst.digest();
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < md.length; i++) {
				int val = md[i] & 0xff;
				if (val < 16) {
					sb.append("0");
				}
				sb.append(Integer.toHexString(val));

			}
			return sb.toString().toLowerCase();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 检查手机网络是否是wifi
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isWifi(Context context) {
		ConnectivityManager connMgr = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
		return networkInfo.getType() == ConnectivityManager.TYPE_WIFI;
	}

	/**
	 * 获得保存mp3文件的目录
	 * @throws IOException 
	 */
	public static String getMp3Path()  {
			File file = null;
			try {
				file = new File( Environment.getExternalStorageDirectory().getCanonicalPath() + "/psct/bg_music/");
			} catch (IOException e) {
				e.printStackTrace();
			}
			if(!file.exists()) {
				file.mkdirs();
			}
			return file.getAbsolutePath();
	}

	/**
	 * 解压缩文件
	 * 
	 * @param unZipfileName
	 * @param mDestPath
	 */
	public static void unZip(String unZipfileName, String mDestPath) {
		if (!mDestPath.endsWith("/")) {
			mDestPath = mDestPath + "/";
		}
		FileOutputStream fileOut = null;
		ZipInputStream zipIn = null;
		ZipEntry zipEntry = null;
		File file = null;
		int readedBytes = 0;
		byte buf[] = new byte[4096];
		try {
			zipIn = new ZipInputStream(new BufferedInputStream(new FileInputStream(unZipfileName)));
			while ((zipEntry = zipIn.getNextEntry()) != null) {
				file = new File(mDestPath + zipEntry.getName());
				if (zipEntry.isDirectory()) {
					file.mkdirs();
				} else {
					// 如果指定文件的目录不存在,则创建之.
					File parent = file.getParentFile();
					if (!parent.exists()) {
						parent.mkdirs();
					}
					fileOut = new FileOutputStream(file);
					while ((readedBytes = zipIn.read(buf)) > 0) {
						fileOut.write(buf, 0, readedBytes);
					}
					fileOut.close();
				}
				zipIn.closeEntry();
			}
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}

	/**
	 * 取得头像的储存目录
	 * 
	 * @return
	 */
	public static String getTempPath(Context context) {
		return ImageCache.getExternalCacheDir(context).getAbsolutePath();
	}

	public static void saveShareImage(Context context, List<String> imagePath) {
		int outHeight = 0;
		int outWidth = 0;
		Bitmap dstBit = null;
		for (int i = 0; i < imagePath.size(); i++) {
			String url = HttpUtil.BASE_URL + "/image/" + imagePath.get(i);
			Bitmap srcBit = ImageCacheManager.getInstance(context).getBitmap(url, null);
			if (srcBit.getWidth() > outWidth)
				outWidth = srcBit.getWidth();
			outHeight += srcBit.getHeight();
			// srcBit.recycle();
		}
		dstBit = Bitmap.createBitmap(outWidth, outHeight, Bitmap.Config.ARGB_8888);
		Canvas canvas = new Canvas(dstBit);
		canvas.drawColor(Color.WHITE);
		Paint paint = new Paint();
		// 用来对位图进行滤波处理
		paint.setFilterBitmap(true);

		int top = 0;
		for (int i = 0; i < imagePath.size(); i++) {
			String url = HttpUtil.BASE_URL + "/image/" + imagePath.get(i);
			Bitmap srcBit = ImageCacheManager.getInstance(context).getBitmap(url, null);
			Rect srcRect = new Rect(0, 0, srcBit.getWidth(), srcBit.getHeight());
			Rect dstRect = new Rect();
			dstRect.set(0, top, srcBit.getWidth(), srcBit.getHeight() + top);
			// 把图片srcBit上srcRect画到dstRect的区域内
			canvas.drawBitmap(srcBit, srcRect, dstRect, paint);
			top += srcBit.getHeight();
			// srcBit.recycle();
		}
		try {
			FileOutputStream fos = context
					.openFileOutput("shared.jpg", Context.MODE_WORLD_READABLE);
			// 经过图像变换之后的Bitmap里的数据可以保存到图像压缩文件里（JPG/PNG）。参数format可设置JPEG或PNG格式；quality可选择压缩质量；fOut是输出流（OutputStream），这里的FileOutputStream是OutputStream的一个子类。
			dstBit.compress(Bitmap.CompressFormat.JPEG, 100, fos);
			Log.v("share", "图片处理完毕");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

	}
}
